package com.berchen.controller;

import com.berchen.common.KeyEnum;
import com.berchen.common.busidb.model.UserVo;
import com.berchen.common.busidb.service.UserService;
import com.berchen.common.result.Result;
import com.berchen.common.result.ResultEnum;
import com.berchen.utils.Log4jUtils;
import com.berchen.utils.OssUtils;
import com.berchen.utils.RedisUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("user")
//@CrossOrigin
public class UserController {
    private static Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserService userService;
    /**
     * 修改用户信息 根据电话号码作为条件
     *
     * @param vo
     * @return
     */
    @PostMapping("update")
    public Result updateUserInfo(@RequestBody @Valid UserVo vo) {
        try {

//            String uid= (String) redisUtils.get(KeyEnum.USER_TOKEN.getKey()+vo.getToken());
//            vo.setId(Long.parseLong(uid));
            // 修改数据
            userService.updateUserInfo(vo);
            return Result.ok();
        } catch (Exception e) {
            logger.error(Log4jUtils.getTrace(e));
            return Result.error();
        }
    }

    /**
     * 修改用户密码
     * @param vo
     * @return
     */
    @PostMapping("update/pass")
    public Result updatePass(@RequestBody @Valid UserVo vo){
        try{
            if(StringUtils.isEmpty(vo.getPassword())){
                return Result.set(ResultEnum.NO_PARAM);
            }
            UserVo query = new UserVo();
            query.setId(vo.getId());
            UserVo userInfo = userService.getUserInfo(query);
            if(vo.getOldPass().equals(userInfo.getPassword())){
                // 可以更改密码
                userService.updatePass(vo);
                return Result.ok();
            }
            else {
                return Result.set(ResultEnum.UPLOAD_PASS_ERROR);
            }
        }catch (Exception e){
            logger.error("修改密码失败："+Log4jUtils.getTrace(e));
            return Result.error();
        }
    }

    /**
     * 上传头像到阿里云 并且保存地址到数据库中
     * @param file
     * @return
     */
    @PostMapping("updateHeadUrl.cwh")
    public Result updateHeadUrl(@RequestParam("file")MultipartFile file, HttpServletRequest request){

        try{
            // 获取用户id
            String token=request.getHeader("token");
            String uid= (String) redisUtils.get(KeyEnum.USER_TOKEN.getKey()+token);
            UserVo vo = new UserVo();
            vo.setId(Long.parseLong(uid));

            //查询数据库 看该用户是否有头像 有就替换 没有就直接上传
            UserVo dbUserVo=userService.getUserInfo(vo);
            String fileName=file.getOriginalFilename();
            String headUrl=null;
            if(StringUtils.isEmpty(dbUserVo.getHeadUrl())){

                // 直接上传到阿里云
                headUrl=OssUtils.uploadFile("headImg",uid,fileName.substring(fileName.lastIndexOf(".")+1), file.getInputStream());
                // 保存路径到用户信息中
                if(StringUtils.isEmpty(headUrl)){
                    return Result.set(ResultEnum.UPLOAD_HEADIMG_ERROR);
                }
                vo.setHeadUrl(headUrl);
                userService.updateUserInfo(vo);
            }
            else {
                // 替换原来头像 删除原来头像 上传新的
                headUrl=OssUtils.updateFile(dbUserVo.getHeadUrl(), file.getInputStream());
            }
            System.out.println(headUrl);
            // 返回头像路径
            return Result.ok(headUrl);
        }catch (Exception e){
            logger.error(Log4jUtils.getTrace(e));
            return Result.error();
        }
    }
}
